# -*- coding: utf-8 -*-
# @Time    : 2020-01-14 10:11
# @Author  : lizhiming    flask可视化模板
# @Email   : 616356241@qq.com
# @File    : app.py

from random import randrange

from flask import Flask, render_template
from flask.json import jsonify
from pyecharts import options as opts
from pyecharts.charts import Bar
import hashlib
import public

from pyecharts.charts import Line

app = Flask(__name__)


def rtmp_info(app, stream):

    str1 = ""+str(bytes(app, encoding = "utf8"))+"_"+str(bytes(stream, encoding = "utf8"))
    path = "/tmp/"+hashlib.md5(str1.encode(encoding='UTF-8')).hexdigest()
    vb = ""
    ab = ""
    vc = ""
    ac = ""
    with open(path+"/rtmp.inf", "r") as f:
        vb = f.readline().replace("\n", "").split(":")
        ab = f.readline().replace("\n", "").split(":")
        vc = f.readline().replace("\n", "").split(":")
        ac = f.readline().replace("\n", "").split(":")

    nx_inf = "视频第一帧快:"
    nx = int(vb[1]) - int(ab[1])
    if nx < 0:
        nx_inf = "音频第一帧快:"
    nx = abs(nx)
    nx_inf = nx_inf +" "+str(nx)+" 毫秒"
    return nx_inf, vc, ac

def bar_video(app, stream) -> Bar:
    
    str1 = ""+str(bytes(app, encoding = "utf8"))+"_"+str(bytes(stream, encoding = "utf8"))
    path = "/tmp/"+hashlib.md5(str1.encode(encoding='UTF-8')).hexdigest()
    t_tm = ""
    t_size = ""
    t_detal = ""
    with open(path+"/rtmp.v", "r") as f:
        t_tm = f.readline().replace("[", "").replace("]", "").replace("\n", "").split(",")
        t_size = f.readline().replace("[", "").replace("]", "").replace("\n", "").split(",")
        t_detal = f.readline().replace("[", "").replace("]", "").replace("\n", "").split(",")

    m_tm = []
    m_size = []
    i = 0
    for a1, a2, a3 in zip(t_tm, t_detal, t_size):
        m = int(a1)+ int(a2)
        m_tm.append(public.tm2hms(m))
        m_size.append(int((int(a3)+1023)/1024))

    c = (
        Bar()
        .add_xaxis(m_tm)
        .add_yaxis("size", m_size, label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(title_opts=opts.TitleOpts(title="", subtitle="视频帧信息"), xaxis_opts=opts.AxisOpts( axislabel_opts={"interval":"5", "rotate":70}))
    )
    return c

def bar_key(app, stream) -> Bar:
    
    str1 = ""+str(bytes(app, encoding = "utf8"))+"_"+str(bytes(stream, encoding = "utf8"))
    path = "/tmp/"+hashlib.md5(str1.encode(encoding='UTF-8')).hexdigest()
    t_tm = ""
    t_size = ""
    t_detal = ""
    with open(path+"/rtmp.k", "r") as f:
        t_tm = f.readline().replace("[", "").replace("]", "").replace("\n", "").split(",")
        t_type = f.readline().replace("[", "").replace("]", "").replace("\n", "").split(",")
        t_detal = f.readline().replace("[", "").replace("]", "").replace("\n", "").split(",")

    m_tm = []
    m_type = []
    i = 0
    for a1, a2, a3 in zip(t_tm, t_detal, t_type):
        m = int(a1)+ int(a2)
        m_tm.append(public.tm2hms(m))
        m_type.append(int(a3))

    c = (
        Bar()
        .add_xaxis(m_tm)
        .add_yaxis("size", m_type, label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(title_opts=opts.TitleOpts(title="", subtitle="关键帧信息"), xaxis_opts=opts.AxisOpts( axislabel_opts={"interval":"5", "rotate":70}))
    )
    return c

def bar_audio(app, stream) -> Bar:
    
    str1 = ""+str(bytes(app, encoding = "utf8"))+"_"+str(bytes(stream, encoding = "utf8"))
    path = "/tmp/"+hashlib.md5(str1.encode(encoding='UTF-8')).hexdigest()
    t_tm = ""
    t_size = ""
    t_detal = ""
    with open(path+"/rtmp.a", "r") as f:
        t_tm = f.readline().replace("[", "").replace("]", "").replace("\n", "").split(",")
        t_size = f.readline().replace("[", "").replace("]", "").replace("\n", "").split(",")
        t_detal = f.readline().replace("[", "").replace("]", "").replace("\n", "").split(",")

    m_tm = []
    m_size = []
    i = 0
    for a1, a2, a3 in zip(t_tm, t_detal, t_size):
        m = int(a1)+ int(a2)
        m_tm.append(public.tm2hms(m))
        m_size.append(int((int(a3)+1023)/1024))
    c = (
        Bar()
        .add_xaxis(m_tm)
        .add_yaxis("size", m_size, label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(title_opts=opts.TitleOpts(title="", subtitle="音频帧信息"), xaxis_opts=opts.AxisOpts( axislabel_opts={"interval":"5", "rotate":70}))
    )
    return c

def line_base() -> Line:
    line = (
        Line()
        .add_xaxis(["{}".format(i) for i in range(10)])
        .add_yaxis(
            series_name="",
            y_axis=[randrange(50, 80) for _ in range(10)],
            is_smooth=True,
            label_opts=opts.LabelOpts(is_show=False),
        ) 
        .set_global_opts(
            title_opts=opts.TitleOpts(title="动态数据"),
            xaxis_opts=opts.AxisOpts(type_="value"),
            yaxis_opts=opts.AxisOpts(type_="value"),
        )
    )
    return line

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/barVideoChart/<app>/<stream>")
def get_bar_vchart(app, stream):
    c = bar_video(app, stream)
    return c.dump_options_with_quotes()


@app.route("/barKeyChart/<app>/<stream>")
def get_bar_kchart(app, stream):
    c = bar_key(app, stream)
    return c.dump_options_with_quotes()

@app.route("/barAudioChart/<app>/<stream>")
def get_bar_achart(app, stream):
    c = bar_audio(app, stream)
    return c.dump_options_with_quotes()

@app.route("/lineChart")
def get_line_chart():
    c = line_base()
    return c.dump_options_with_quotes()

idx = 9

@app.route("/lineDynamicData")
def update_line_data():
    global idx
    idx = idx + 1
    return jsonify({"name": idx, "value": randrange(50, 80)})


# @app.route("/index/line")
# def line():
#     return render_template("line_on.html")


@app.route("/rtmp/<app>/<stream>")
def line(app, stream):

    inf, vc, ac = rtmp_info(app, stream)
    context = {
        "app":app,
        "stream":stream,
        "tnx":inf,
        vc[0]:vc[1],
        ac[0]:ac[1]
    }
    return render_template("index.html", **context)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)